extends KinematicBody2D

# 逻辑加速度，实现方案：每帧加上一个速度
const ACCELERATION = 10
# 最大速度因子
const MAX_SPEED = 100
# 逻辑摩擦力，实现方案：使用Vecotr2D.move_toward()函数
const FRICTION = 10

const ROLL_SPEED = 112

export (float) var INVINCIBAL_DURATION = 1.2

enum {
	MOVE,
	ROLL,
	ATTACK
}

var state = MOVE

# 控制任务移动，采用物理引擎来实现，更容易达到符合体感的效果
var velocity = Vector2.DOWN
var roll_vector = Vector2.DOWN
var stats = PlayerStats

var PlayerHurtSound = preload("res://Player/PlayerHurtSound.tscn")

onready var animationTree = $AnimationTree
onready var animationState = animationTree.get("parameters/playback")

onready var swordHitbox = $"HitboxPivot/SwordHitbox"
onready var hurtBox =$HurtBox
onready var blinkAnimationPlayer = $BlinkAnimationPlayer

func _ready():
	randomize()
	# 这里简单演示下，玩家生命值结束的回调
	stats.connect("no_health", self, "queue_free")
	
	animationTree.active = true
	swordHitbox.knockback_vector = roll_vector

func _physics_process(delta):
	match state:
		MOVE:
			move_state(delta)
		ROLL:
			roll_state(delta)
		ATTACK:
			attack_state(delta)

func move_state(delta):
	var input_vector = Vector2.ZERO
	input_vector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
	input_vector.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
	#处理x y方向都有值时的情况
	input_vector = input_vector.normalized()
	
	if input_vector != Vector2.ZERO:
		roll_vector = input_vector
		swordHitbox.knockback_vector = input_vector
		animationTree.set("parameters/Idle/blend_position", input_vector)
		animationTree.set("parameters/Run/blend_position", input_vector)
		#animationTree.set("parameters/Attack/blend_position", input_vector)
		animationTree.set("parameters/Roll/blend_position", input_vector)
		animationState.travel("Run")
		velocity = velocity.move_toward(input_vector * MAX_SPEED, ACCELERATION)
	else :
		animationState.travel("Idle")
		velocity = velocity.move_toward(Vector2.ZERO, FRICTION)
	
	# 沿着向量移动，碰撞后停止，对于rpg的游戏角色移动不友好
	#move_and_collide(velocity * delta)
	# 可以沿着碰撞边缘移动，并自动处理了delta
	move()
	
	if Input.is_action_just_pressed("attack"):
		state = ATTACK
	if Input.is_action_just_pressed("roll"):
		state = ROLL

func attack_state(delta):
	animationTree.set("parameters/Attack/blend_position", roll_vector)
	velocity = Vector2.ZERO
	animationState.travel("Attack")

func roll_state(delta):
	velocity = roll_vector * ROLL_SPEED
	animationState.travel("Roll")
	move()
	
func move():
	velocity = move_and_slide(velocity)

func attack_animation_finished():
	state = MOVE

func roll_animation_finished():
	velocity = velocity * 0.8
	state = MOVE

func _on_HurtBox_area_entered(area):
	stats.health -= area.damage
	hurtBox.start_invincibility(INVINCIBAL_DURATION)
	hurtBox.create_hit_effect()
	var playerHurtSound = PlayerHurtSound.instance()
	get_tree().current_scene.add_child(playerHurtSound)
	

func _on_HurtBox_invincibility_started():
	blinkAnimationPlayer.play("Start")


func _on_HurtBox_invincibility_ended():
	blinkAnimationPlayer.play("Stop")
